import 'package:casdon/core/logger/log.dart';
import 'package:casdon/core/network/business_exception.dart';

import 'package:casdon/modules/login/data/repository/auth_repository.dart';
import 'package:casdon/modules/login/domain/validators/input_validator.dart';
import 'package:casdon/modules/login/providers/login_provider.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

class RegisterUsecase {
  final AuthRepository repository;
  final InputValidator validator;
  final InputValidator passwordValidator;
  const RegisterUsecase(
    this.repository,
    this.validator,
    this.passwordValidator,
  );

  Future<bool> execute({
    required String userName,
    required String grantType,
    required String password,
  }) async {
    if (validator.isValude(userName) == false) {
      throw "账号格式不正确";
    }
    if (passwordValidator.isValude(password) == false) {
      throw "密码不合规";
    }
    try {
      final _ = await repository.postRegister(userName, grantType, password);
      return true;
    } on BusinessException catch (e) {
      Log.d("注册失败：${e.msg}");
      rethrow;
    } catch (e) {
      return false;
    }
  }
}

// 注册
final registerUsecaseProvider = Provider(
  (ref) => RegisterUsecase(
    ref.read(authRepositoryProvider),
    ref.read(inputValidatorProvider),
    ref.read(passwordValidatorProvider),
  ),
);
